package cn.itheima.service;

import cn.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MyDetailService  implements UserDetailsService {

    @Autowired
    BCryptPasswordEncoder  bCryptPasswordEncoder;
    //    模拟数据库 完成用户权限或者角色关键字查询
    //   lisi    ROLE_FIND, DELTE     zs    ROLE_ADD , QUERY    123
    Map<String,User> map  = new HashMap<String,User>();

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initData();
                //   2  通过账号 查询 数据库 用户信息    给两个用户创建权限或者角色
          if("zs".equals(username)){
              User user = map.get(username);  //   数据库 zs信息
              String  name = user.getName();
              String password = user.getPassword();
              List<GrantedAuthority> list  = new ArrayList<GrantedAuthority>();
              list.add(new SimpleGrantedAuthority("ROLE_ADD"));
              list.add(new SimpleGrantedAuthority("QUERY"));
              return  new org.springframework.security.core.userdetails.User(name,password,list);

          }
        if("lisi".equals(username)){
            User user = map.get(username);  //   数据库 zs信息
            String  name = user.getName();
            String password = user.getPassword();
            List<GrantedAuthority> list  = new ArrayList<GrantedAuthority>();
            list.add(new SimpleGrantedAuthority("ROLE_FIND"));
            list.add(new SimpleGrantedAuthority("DELETE"));
            return  new org.springframework.security.core.userdetails.User(name,password,list);

        }
        //    loadUserByUsername  返回值null  认证失败！
        return null;
    }

    private void initData() {

        System.out.println(bCryptPasswordEncoder.encode("123")+"----");
        System.out.println(bCryptPasswordEncoder.encode("123")+"-====");
       //  密码 加密处理
        User  user1 = new User(1,"zs",bCryptPasswordEncoder.encode("123"));
        User  user2 = new User(2,"lisi",bCryptPasswordEncoder.encode("123"));
        map.put("zs",user1);
        map.put("lisi",user2);

    }
}
